var fs=require('fs');
var conn=require('connect');
var http=require('http');
var app=conn();
var timeout=require('./timeout');
var responseTime=require('./responseTime');

/*日志*/
app.use(function (req, res, next) {
    console.log('----------------------------------------');
    console.log('[',new Date(),']:',req.method,'-',req.url);
    next();
});

/*响应时长*/
app.use(responseTime());

/*超时*/
app.use(timeout({time:10}));

/*图片*/
app.use(function (req, res, next) {
   if('GET'==req.method && '/img'==req.url.substr(0,4)){
       fs.stat(__dirname+'/website'+req.url, function (err, st) {
          if(st && st.isFile()){
              send(res,__dirname+'/website'+req.url,'application/png');
          }else{
              send404(res);
          }
       });
   }else{
       next();
   }
});

/*html*/
app.use(function (req, res, next) {
   if('GET'==req.method && '/'==req.url){
       send(res,__dirname+'/website/index.html','text/html');
   }else{
       next();
   }
});

http.createServer(app).listen(3000, function () {
    console.log('port 3000');
});

function send(res,_url,type){
    setTimeout(function(){//模拟网络延时
        res.writeHead(200,{'content-type':type});
        console.log('send url:',_url);
        fs.createReadStream(_url).pipe(res);
    },Math.random()*100|0);
}

function send404(res){
    res.writeHead(404);
    res.end('Not Found');
}